package com.hmdp.service.impl;

import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.locks.Lock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisWorker redisWorker;

//    @Resource
//    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedissonClient redissonClient;

    @Override
    public Result sekillVoucher(Long voucherId) {


        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始！");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束!");
        }
        if (seckillVoucher.getStock() < 1) {
            return Result.fail("库存不足！");
        }
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //synchronized解决一人一单
        //减小锁的粒度，提交事务后再释放锁，防止释放锁没提交线程导致有进来的线程导致的线程安全问题
//        synchronized (userId.toString().intern()) {
//            //获取代理对象，spring事务交给代理对象执行
//            /*
//            spring事务交给代理对去执行，此处需要获取代理对象与来执行方法
//            1.引入依赖
//            <dependency>
//            <groupId>org.aspectj</groupId>
//            <artifactId>aspectjweaver</artifactId>
//            </dependency>
//            2.开启暴露代理对象
//            @EnableAspectJAutoProxy(exposeProxy = true)
//            */
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createOrder(voucherId, user);
//        }
        //2.分布式锁解决一人一单

        //创建锁对象
        //SimpleRedisLock lock  = new SimpleRedisLock(stringRedisTemplate,"order:" + userId);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean b = lock.tryLock();
        if(!b){
            //获取锁失败
            return Result.fail("一人一单，不可重复购买!");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createOrder(voucherId, user);
        }finally {
            lock.unlock();
        }


    }

    @Transactional
    public Result createOrder(Long voucherId, UserDTO user) {

        Long id = user.getId();
        //一人一单校验
        int count = query().eq("user_id", user.getId()).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("一人限购一单，不可重复购买！");
        }
        //扣减库存，更新的时候可以采用乐观锁来监视更新之前的数据有没有被其他线程更改过
        //查询的时候判断是否存在，只能通过加锁的方式同步执行
        boolean success = seckillVoucherService.update().setSql("stock = stock -1")
                .gt("stock", 0)
                .eq("voucher_id", voucherId).update();
        if (!success) {
            return Result.fail("扣减失败，库存不足");
        }
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long order = redisWorker.nextId("order");
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(order);
        voucherOrder.setUserId(user.getId());
        save(voucherOrder);
        return Result.ok(order);
    }
}
